package com.example.personblog.utils;

import com.example.personblog.repository.PostRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Slf4j
@Component
@EnableScheduling
public class ViewTaskUtil {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private PostRepository postRepository;
    
    private static final String VIEW_KEY = "post:view:";
    private static final String LIKE_KEY = "post:like:";
    
    /**
     * 每5分钟同步浏览量和点赞数据到数据库
     */
    @Scheduled(fixedRate = 300000)
    @Transactional(rollbackFor = Exception.class)
    public void syncDataToDB() {
        // 同步浏览量
        syncViewsToDB();
        // 同步点赞数
        syncLikesToDB();
    }
    
    /**
     * 同步浏览量数据
     */
    @Scheduled(fixedRate = 300000)
    @Transactional(rollbackFor = Exception.class)
    public void syncViewsToDB() {
        log.info("开始同步浏览量数据到数据库...");
        try {
            Set<String> keys = redisTemplate.keys(VIEW_KEY + "*");
            if (keys != null) {
                for (String key : keys) {
                    String postId = key.substring(VIEW_KEY.length());
                    Object viewCount = redisTemplate.opsForValue().get(key);
                    if (viewCount != null) {
                        postRepository.updateViews(Long.valueOf(postId), 
                                Long.valueOf(viewCount.toString()));
                    }
                }
            }
            log.info("同步浏览量数据完成");
        } catch (Exception e) {
            log.error("同步浏览量数据失败", e);
            throw e;
        }
    }
    
    /**
     * 同步点赞数据
     */
    private void syncLikesToDB() {
        log.info("开始同步点赞数据到数据库...");
        try {
            Set<String> keys = redisTemplate.keys(LIKE_KEY + "*");
            if (keys != null) {
                for (String key : keys) {
                    String postId = key.substring(LIKE_KEY.length());
                    Long likeCount = redisTemplate.opsForSet().size(key);
                    if (likeCount != null) {
                        postRepository.updateLikeCount(Long.valueOf(postId), likeCount);
                    }
                }
            }
            log.info("同步点赞数据完成");
        } catch (Exception e) {
            log.error("同步点赞数据失败", e);
            throw e;
        }
    }
} 